#pragma once

#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include"Logger.hpp"
#include<netinet/in.h>
#include<arpa/inet.h>
#include<strings.h>

class UdpServer
{   
public:
    UdpServer(uint16_t port)
        :_socket_fd(-1)
        ,_port(port)
        ,_is_running(false)
    { }

    void Init()
    {
        _socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_socket_fd < 0)
        {
            LOG(LogLevel::FATAL) << "create socket error";
            exit(1);
        }
        LOG(LogLevel::INFO) << "create socket success:" << _socket_fd;
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        //local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        int ret = bind(_socket_fd, (struct sockaddr*)&local, sizeof(local));
        if(ret < 0)
        {
            LOG(LogLevel::FATAL) << "bind socket error";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind socket success";
    }

    void Start()
    {
        _is_running = true;
        while(_is_running)
        {
            char buffer[1024];
            buffer[0] = 0;
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t ret = recvfrom(_socket_fd, buffer, sizeof(buffer), 0, 
                              (struct sockaddr*)&peer, &len);
            if(ret > 0)
            {
                buffer[ret] = 0;
                uint16_t client_port = peer.sin_port;
                std::string client_ip = inet_ntoa(peer.sin_addr);
                LOG(LogLevel::DEBUG) << "[" << client_ip << ":" << client_port 
                                     << "]#" << buffer; 
                //LOG(LogLevel::DEBUG) << "client say# " << buffer;
                std::string echo = "server echo# ";
                echo += buffer;
                sendto(_socket_fd, echo.c_str(), echo.size(), 0, 
                      (struct sockaddr*)&peer, len);
            }
        }
        _is_running = false;
    }

    void Stop()
    {
        _is_running = false;
    }

private:
    //std::string _ip;
    int _socket_fd;
    uint16_t _port;
    bool _is_running;
};